import { constantRoutes } from "@/router"
//
import { getInfo } from "@/api/user"
// import { removeToken } from "@/utils/auth"
import Layout from "@/layout"
/**
 * Use meta.role to determine if the current user has permission
 * @param roles
 * @param route
 */
// function hasPermission(roles, route) {
//   if (route.meta && route.meta.roles) {
//     return roles.some((role) => route.meta.roles.includes(role));
//   } else {
//     return true;
//   }
// }

/**
 * Filter asynchronous routing tables by recursion
 * @param routes asyncRoutes
 * @param roles
 */
export function filterAsyncRoutes(arr) {
  const res = []
  let obj = {}
  arr.forEach((el) => {
    // debugger
    if (el.checked === "0") {
      return
    }
    if (el.children.length === 0) {
      obj = {
        path: "/" + el.path,
        component: Layout,
        children: [
          {
            path: "index",
            name: "Index",
            component: loadView(el.component),
            // meta: { title: el.menuName, icon: el.menuIcon }
            meta: el.meta
          }
        ]
      }
    } else {
      obj = {
        path: "/" + el.path,
        component: Layout,
        // redirect: `/${el.menuUrl}/${el.children[0].menuUrl}`,
        name: el.path,
        // meta: { title: el.menuName, icon: el.menuIcon },
        meta: el.meta,
        children: []
      }
      el.children.forEach((son) => {
        obj.children.push({
          path: son.path,
          name: son.path,
          component: loadView(son.component),
          // meta: { title: son.menuName, icon: son.menuIcon }
          meta: son.meta
        })
      })
    }
    res.push(obj)
  })
  return res
}

export const loadView = (view) => {
  return (resolve) => require([`@/views/${view}`], resolve)
}

const state = {
  routes: [],
  addRoutes: [],
  buttonList: [],
  routeLen: 0
}

const mutations = {
  SET_ROUTES: (state, routes) => {
    state.addRoutes = routes
    state.routeLen = constantRoutes.length
    state.routes = constantRoutes.concat(routes)
  },
  SET_BUTTON: (state, buttonList) => {
    state.buttonList = buttonList
  },
}

const actions = {
  generateRoutes({ commit }) {
    const token = localStorage.getItem("token")
    // console.log(roleCode, "权限")
    return new Promise((resolve) => {
      getInfo(token).then((res) => {
        const accessedRoutes = filterAsyncRoutes(res.object.router) || []
        const buttonList = []
        commit("SET_ROUTES", accessedRoutes)
        commit("SET_BUTTON", buttonList)
        resolve(accessedRoutes)
      })
    })
  },
  // user logout
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      // removeToken()
      sessionStorage.clear()
      commit("SET_ROUTES", [])
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}
